import browser_cookie3
from http.cookiejar import CookieJar
import sys
from time import time


class BrowserCookiesGetter:
    pixiv_domain = '.pixiv.net'
    current_time = time()

    def get_cookies_automatically_from_browser(self) -> CookieJar | None:
        cookies_from_chrome = self.__get_cookies_from_chrome()
        cookies_from_firefox = self.__get_cookies_from_firefox()
        cookies_from_edge = self.__get_cookies_from_edge()

        if self.__cookie_is_valid(cookies_from_chrome):
            return cookies_from_chrome
        elif self.__cookie_is_valid(cookies_from_firefox):
            return cookies_from_firefox
        elif self.__cookie_is_valid(cookies_from_edge):
            return cookies_from_edge
        else:
            print('Cannot fetch any cookie from Chrome, Firefox or Edge.', file=sys.stderr)
            return None

    def __get_cookies_from_firefox(self) -> CookieJar | None:
        try:
            return browser_cookie3.firefox(domain_name=self.pixiv_domain)
        except Exception as e:
            print(f'No cookies of {self.pixiv_domain} found in Mozilla Firefox: {e}', file=sys.stderr)
            return None

    def __get_cookies_from_edge(self) -> CookieJar | None:
        try:
            return browser_cookie3.edge(domain_name=self.pixiv_domain)
        except Exception as e:
            print(f'No cookies of {self.pixiv_domain} found in Microsoft Edge: {e}', file=sys.stderr)
            return None

    def __get_cookies_from_chrome(self) -> CookieJar | None:
        try:
            return browser_cookie3.chrome(domain_name=self.pixiv_domain)
        except Exception as e:
            print(f'No cookies of {self.pixiv_domain} found in Google Chrome: {e}', file=sys.stderr)
            return None

    # TODO: expiration detection
    def __cookie_is_valid(self, cookies: CookieJar | None) -> bool:
        # if cookies is None:
        #     return False
        # for cookie in cookies:
        #     if cookie.expires is not None:
        #         if cookie.expires <= self.current_time:
        #             return False
        # return True
        return cookies is not None
